<?php

namespace App\Http\Controllers\PhpCookBook\Arr;

use App\BCAM\CMVariable\CMVariable;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ChangeTypeController extends Controller
{
    //4.8 将数组转换为字符串
    public function arrayImplode(){
        //join是implode的别名
        $string = implode(',',[1,2,3,4]);

        //只会在两个元素中间放入,单元素的数组,一个巴掌拍不响
        $stringO = implode(',',[1]);

        $stingCom = $this->arrayToCommaString([1,2,3]);
        //报错,不能处理多维数组,除非手动对数组做扁平化处理
        //$stringArr = implode(',',[1,[2,3]]);

        CMVariable::compareRes($string,$stringO,$stingCom);
    }

    public function arrayToCommaString($array){
        switch(count($array)){
            case 0:
                return '';
            case 1:
                return reset($array);
            case 2:
                return join(' and ',$array);
            default:
                $last = array_pop($array);
                return join(', ',$array).', and '.$last;
        }
    }
}
